package cn.jinjimi.domain.data.imp;

import cn.jinjimi.base.preference.PreferenceManager;
import cn.jinjimi.app.controller.event.DataEvent;
import cn.jinjimi.app.controller.event.PersonalPhotoUploadEvent;
import cn.jinjimi.app.controller.event.UploadResultEvent;
import cn.jinjimi.domain.data.Store;
import cn.jinjimi.domain.data.net.API;
import cn.jinjimi.domain.data.net.FileService;
import cn.jinjimi.domain.store.FileStore;
import cn.jinjimi.app.entity.Avatar;
import cn.jinjimi.app.bean.SharePrefKeys;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 *
 * @author zhenhua
 * @date 16/8/1
 */
public class FileStoreImp extends Store implements FileStore {

    private List<MultipartBody.Part> convert2Parts(HashMap<String, Object> params) {

        if (params == null) {
            return null;
        }

        List<MultipartBody.Part> parts = new ArrayList<>();

        MediaType file = MediaType.parse("application/octet-stream");
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if (entry.getValue() instanceof MultipartBody.Part) {
                parts.add((MultipartBody.Part) entry.getValue());
            } else if (entry.getValue() instanceof File) {
                RequestBody rb = RequestBody.create(file, (File) entry.getValue());
                MultipartBody.Part part = MultipartBody.Part.createFormData("file", ((File) entry.getValue()).getName(), rb);
                parts.add(part);
            } else {
                MultipartBody.Part part = MultipartBody.Part.createFormData(entry.getKey(), (String) entry.getValue());
                parts.add(part);
            }
        }

        return parts;
    }

    @Override
    public UploadResultEvent upload(String url, HashMap<String, Object> params) throws IOException {

        UploadResultEvent event = new UploadResultEvent();

        if (params == null || params.isEmpty()) {
            event.state = DataEvent.FAIL;
            return event;
        }

        List<MultipartBody.Part> parts = convert2Parts(params);
        Response<ResponseBody> response = API.create(FileService.class).upload(url, parts).execute();

        if (response == null) {
            event.state = DataEvent.FAIL;
            return event;
        }

        if (response.isSuccessful()) {
            event.state = DataEvent.SUCC;
            event.data = response.body().string();
        } else {
            event.state = DataEvent.FAIL;
            event.error = response.code();
            event.msg = response.message();
        }

        return event;
    }


}
